<template>
  <div class="addPointType">
    <el-form :model="editForm" label-width="100px" :rules="rules" @submit.native.prevent  ref="editForm">
      <el-row type="flex" justify="center">
        <el-col :span="20">
          <el-form-item
            label="类别名称："
            prop="pointTypeName">
            <el-input
              v-model.trim="editForm.pointTypeName"
              placeholder="不要重复">
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 显示检查内容 -->
      <el-row v-if="reserveInspectContent.length > 0">
        <detail-message :contents="reserveInspectContent" @editInspectItem="editInspectItem" @deleteInspectItem="deleteInspectItem" :isDetailClick="false" />
      </el-row>

      <el-row v-for="(item, index) in inspectContent" :key="index" class="inspectContent">
        <el-col :span="20">
          <div>检查内容{{currentEditIndex + 1}}</div>
          <el-form-item 
            label="内容名称：">
            <el-input placeholder="请输入内容名称" type="text" v-model.trim="item.content"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="20">
          <el-form-item
            label="检查类型：">
            <el-radio-group v-model="item.optionType">
              <el-radio :label="1">合格/不合格类</el-radio>
              <el-radio :label="2">单选类</el-radio>
              <el-radio :label="3">填值类</el-radio>
              <el-radio :label="4">拍照类</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="20" class="inspectContent_selectItem">
  
          <!-- 合格/不合格类 -->
          <template v-if="item.optionType === 1">
            <el-row class="inspectContent_selectItem_qualification">
              <el-row class="inspectContent_selectItem_qualification_qualified">
                <el-col :span="16">
                  <el-input placeholder="" value="A：合格" disabled></el-input>
                </el-col>
              </el-row>
              <el-row type="flex" justify="space-between" class="inspectContent_selectItem_qualification_unqualified">
                <el-col :span="16">
                  <el-input placeholder="" value="B：不合格" disabled></el-input>
                </el-col>
                <el-col :span="6">
                  <el-checkbox checked disabled>设为不合格</el-checkbox>
                </el-col>
              </el-row>
            </el-row>
          </template>

          <!-- 单选类  -->
          <template v-if="item.optionType === 2">
            <el-row v-for="(attrItem , attrIndex) in item.attr" :key="attrIndex" type="flex" justify="space-between" class="inspectContent_selectItem_singleSelect" 
            @mouseenter.native="showDelete" @mouseleave.native="hiddenDelete">
              <el-col :span="16" class="inspectContent_selectItem_singleSelect_input">
                <el-input v-model.trim="attrItem.option" :placeholder="'请输入选项'+ ' ' + printLetters(attrIndex)"  ></el-input>
              </el-col>
              <el-col :span="1" v-if="isShowDelete" style="font-size: 16px;" @click.native="deleteAttrItem(item.attr,attrIndex)">
                <i class="el-icon-close"></i>
              </el-col>
              <el-col :span="6">
                <el-checkbox :checked="attrItem.isOk === 1 ? false : true" @change=" attrItem.isOk = (attrItem.isOk === 1 ? 2 : 1)" :key="attrItem.isOk">设为不合格</el-checkbox>
              </el-col>
            </el-row>
            <el-row>
              <el-col>
                <el-button type="primary" plain @click="addSingleSelectItem(index)" >+ 添加选项</el-button>
              </el-col>
            </el-row>
          </template>

          <!-- 填值类 -->
          <template v-if="item.optionType === 3">
            <el-row class="inspectContent_selectItem_inputContent">
              <el-col :span="16" class="inspectContent_selectItem_inputContent_i">
                <span>上限：</span>
                <el-input v-model.number="item.upperLimit" type="number" placeholder="请输入数字" @keydown.native="channelInputLimit"></el-input>
              </el-col>
              <el-col :span="16" class="inspectContent_selectItem_inputContent_i">
                <span>下限：</span>
                <el-input v-model.number="item.lowerLimit" type="number" placeholder="请输入数字" @keydown.native="channelInputLimit"></el-input>
              </el-col>
              <el-col :span="16" class="inspectContent_selectItem_inputContent_i">
                <span>单位：</span>
                <el-input v-model.trim="item.unit" type="text" placeholder="请输入单位，比如米"></el-input>
              </el-col>
            </el-row>       
          </template>

          <!-- 拍照类 -->
          <template v-if="item.optionType === 4">
            <el-row class="inspectContent_selectItem_photograph">
              <el-col :span="16" class="inspectContent_selectItem_photograph_i">
                <span>最少拍照数量：</span>
                <el-input v-model.number="item.photographNumber" type="number" max="9" placeholder="输入数字，不超过9张" @keydown.native="channelInputLimit"></el-input>
                <span style="margin-left: 8px;">张</span>
              </el-col>
            </el-row>
          </template>

          <el-col :span="24" class="inspectContent_button">
            <el-button type="primary" @click="confirm(item,index)">确定</el-button>
            <el-button type="primary" @click="cancel(index)">取消</el-button>
          </el-col>
        </el-col>
      </el-row>
      <el-row type="flex" justify="center">
        <el-col :span="20" class="addInspectContentButton">
          <el-button type="primary" plain @click="addInspectContent('editForm')" round>
            +&nbsp;&nbsp;&nbsp;&nbsp;添加检查内容
          </el-button>

          <el-button type="primary" plain @click="savePointType('editForm')" round>
            保存点位类别
          </el-button>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import DetailMessage from './DetailMessage'

import { addInspectPointType, getPointTypeInfo} from '@/api/inspectx'

export default {
  components: {
    DetailMessage
  },
  props: {
    editInfo: {
      type: Object,
      require: true
    },
    handleClose: {
      type: Function,
      require: true
    }
  },
  data() {
    return {
      inspectContent: [              // 检查内容
        // {
        //   content: '',
        //   attr: [],
        //   optionType: '',
        //   upperLimit: '',         // 上限
        //   lowerLimit: '',         // 下限
        //   unit: '',               // 单位
        //   photographNumber: '',   // 拍照数量
        // }
      ],

      isEditStatus: false,            // 编辑检查内容状态

      currentEditIndex: '',           // 当前编辑的下标，或当前编辑的检查内容的下标

      reserveInspectContent: [],      // 保存检查内容

      isShowDelete: false,            // 不显示删除图标

      // isEditContent: false,           // 编辑

      editForm: {
        id: '',
        orgId: this.$store.state.userinfo.org.id,
        pointTypeName: '',
        picUrl: '',
        createAccount: this.$store.state.userinfo.accountName,
        updateAccount: this.$store.state.userinfo.accountName,
        contents: ''
      },

      rules: {                              // 约束规则
        pointTypeName: [
          { required: true, message: '请输入点位类别名称', trigger: 'blur'}
        ]
      }
    }
  },
  created() {
    if(Object.keys(this.editInfo).length !== 0) {

      // this.isEditContent = true

      console.log('编辑')

      this.editForm.pointTypeName = this.editInfo.pointTypeName 

      getPointTypeInfo({pointTypeId: this.editInfo.id}).then(res => {
        this.reserveInspectContent = this.formatContents(res.data.contents)

        console.log(res.data.contents);
      })

    }else {
      console.log('新增');
    }
  },
  methods: {
    
    // 添加检查内容
    addInspectContent(params) {
      this.$refs[params].validate((valid) => {
        if(valid) {
          if(!this.inspectContent.length) {
            this.inspectContent.push({
              content: '',                  // 检查内容
              attr: [                       // 类别内容
                {
                  option: '', 
                  isOk: 1                   // 合格项
                },
                { 
                  option: '', 
                  isOk: 2                   // 不合格项
                }
              ],                     
              optionType: '',               // 检查类别
              upperLimit: '',               // 上限
              lowerLimit: '',               // 下限
              unit: '',                     // 单位
              photographNumber: '',         // 拍照数量
            })
          }else {
            this.printError('请将当前检查内容填写完整并点击确认按钮！！！')
          }
        }
      })
    },

    // 保存点位类别
    savePointType(params) {
      this.$refs[params].validate((valid)=> {
        if(valid){
          if(!this.reserveInspectContent.length) {
            this.printError('请添加检查内容！！！')
            return
          }

          if(this.inspectContent.length) {
            this.printError('请将当前检查内容填写完整并点击确认按钮！！！')
            return
          }

          let photographLength = this.reserveInspectContent.filter( item => {
            return item.optionType === 4
          })

          if(this.reserveInspectContent.length === photographLength.length) {
            this.printError('不允许只有拍照类的检查内容')
            return
          }

          let contents = []

          this.reserveInspectContent.forEach((parentItem, parentIndex, parentArray) => {
            contents.push({
              name: parentItem.content,
              sort: 1,
              checkType: parentItem.optionType,
              options: []
            })

            // 合格不合格类
            if(parentItem.optionType === 1) {
              contents[parentIndex].options.push(
                {
                  option: '合格',
                  isOk: 1,
                  lable: 'A'
                }, 
                {
                  option: '不合格',
                  isOk: 2,
                  lable: 'B'
                }
              )
            }

            // 单选类
            if(parentItem.optionType === 2) {
              parentItem.attr.forEach((childItem, childIndex, childArray) => {
                contents[parentIndex].options.push({
                  option: childItem.option,
                  isOk: childItem.isOk,
                  lable: childIndex + 1
                })
              })
            }

            // 填值类
            if(parentItem.optionType === 3) {
              contents[parentIndex].options.push(
                {
                  option: parentItem.upperLimit,
                  isOk: 1,
                  lable: 'A'
                },
                {
                  option: parentItem.lowerLimit,
                  isOk: 1,
                  lable: 'B'
                },
                {
                  option: parentItem.unit,
                  isOk: 1,
                  lable: 'C'
                }
              )
            }

            // 拍照
            if(parentItem.optionType === 4) {
              contents[parentIndex].options.push(
                {
                  option: parentItem.photographNumber,
                  isOk: 1,
                  lable: 1
                }
              )
            }
          })

          let data = {
            name: this.editForm.pointTypeName,
            orgId: this.editForm.orgId,
            contents
          }

          // 新增点位类别
          addInspectPointType(data).then(res => {
            if(res.status === 200) {
              this.$message({
                message: '保存成功',
                type: 'success'
              })
            }
            this.handleClose(true)
          })
        }
      })
    },
    
    // 显示删除按钮
    showDelete() {
      this.isShowDelete = true
    },

    // 隐藏删除按钮
    hiddenDelete() {
      this.isShowDelete = false
    },

    // 点击删除按钮
    deleteAttrItem(attr,index) {
      if(attr.length > 2){
        attr.splice(index,1)
        return
      }
      this.printError('单选项至少有两项！！！')
    },

    // 保存检查项
    confirm(item,index) {
      let {
        content,
        attr,
        optionType,
        upperLimit,
        lowerLimit,
        unit,
        photographNumber
      } = item

      if(!content){
        this.printError('请输入检查项内容名称！！！')
        return 
      }

      if(!optionType) {
        this.printError('请选择检查类型！！！')
        return
      }

      switch(optionType) {
        case 1:
          break
        case 2:
          let isOptionFlag = attr.some((item, index) => {
            return item.option === ''
          })
          if(isOptionFlag) {
            this.printError('请将单选项输入完整！！！')
            return 
          }

          let isHasTrue = attr.some((item, index) => {
            return item.isOk === 1
          })
          if(!isHasTrue) {
            this.printError('单选项至少有一项是合格项！！！')
            return
          }

          let isHasFalse = attr.some((item, index) => {
            return item.isOk === 2
          })
          if(!isHasFalse) {
            this.printError('单选项至少有一项是不合格项！！！')
            return
          }
          break
        case 3:
          if(upperLimit === '') {
            this.printError('请输入上限值！！！')
            return
          } 
          if(lowerLimit === '') {
            this.printError('请输入下限值！！！')
            return
          }
          if(!unit) {
            this.printError('请输入单位！！！')
            return
          }
          break
        case 4:
          if(photographNumber === '') {
            this.printError('请输入最小拍照数量！！！')
            return
          }
          if(photographNumber <= 0 || photographNumber > 9) {
            this.printError('最小拍照数量不在有效范围内！！！')
            return
          }
          break
        default: 
          this.printError('error:system exception')
          return
      }

      if(this.isEditStatus) {
        this.reserveInspectContent.splice(this.currentEditIndex,1,item)
        this.inspectContent.splice(index,1)    // 编辑的检查内容框
        this.isEditStatus = false
        return
      }
      this.reserveInspectContent.push(item)  // 保存检查项
      this.inspectContent.splice(index,1)    // 删除已保存检查项
      this.currentEditIndex = this.reserveInspectContent.length // 设置当前检查内容的索引
    },

    // 取消检查项
    cancel(index) {
      this.inspectContent.splice(index,1)
    },

    // 编辑检查项 
    editInspectItem(index) {
      // 编辑状态
      this.isEditStatus = true
      // 防止响应显示
      let inspectItem = JSON.parse(JSON.stringify(this.reserveInspectContent[index]))
      // 置空
      this.inspectContent = []
      // 设置当前编辑内容
      this.inspectContent.push(inspectItem)
      // 当前编辑的检查内容索引
      this.currentEditIndex = index
    },

    // 删除检查项 
    deleteInspectItem(index) {
      this.reserveInspectContent.splice(index,1)
      this.currentEditIndex = this.reserveInspectContent.length
    },

    // 添加单选项 params:index
    addSingleSelectItem(index) {
      this.inspectContent[index].attr.push({
        option: '',
        isOk: 2         // 不合格项
      })
    },

    // 不允许输入'e'和'.'
    channelInputLimit (e) {
      let key = e.key
      if (key === 'e' || key === '.') {
        e.returnValue = false
        return false
      }
      return true
    },

    // 输出字母
    printLetters(attrIndex) {
      let letters = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
      return letters.find((item ,index) => {
        return index === attrIndex
      })
    },

    // 输出警告消息
    printError(msg) {
      this.$message({
        message: msg,
        type: 'error'
      })
    },

    // 格式化
    formatContents(contents) {
      let contentsList = []
      contents.forEach((item, index) => {
        let attr = []
        
        let upperLimit = item.checkType === 3 ? item.options[0].option : ''

        let lowerLimit = item.checkType === 3 ? item.options[1].option : ''
        
        let unit =  item.checkType === 3 ? item.options[2].option : ''

        let photographNumber =  item.checkType === 4 ? item.options[0].option : ''

        if(item.checkType === 2 || item.checkType === 1) {
          item.options.forEach((item, index) => {
            attr.push({
              option: item.option,
              isOk: item.isOk
            })
          })
        }

        contentsList.push({
          content: item.name,
          optionType: item.checkType,
          attr,
          upperLimit,
          lowerLimit,
          unit,
          photographNumber
        })

      })

      return contentsList
    }
  }
}
</script>

<style lang="scss">

.addPointType {
  .inspectContent {
    padding-top: 20px;
    background-color: #e7f2f4;
    margin-bottom: 20px;
    display: flex;
    flex-direction: column;
    align-items: center;
    .el-form-item__label {
      font-weight: normal;
    }
    .el-radio {
      margin-right: 10px;
    }
    .el-radio__label {
      padding-left: 5px;
    }
    .el-col-6 {
      display: flex;
      align-items: center;
    }
    .el-col-1 {
      display: flex;
      align-items: center;
    }
    .inspectContent_selectItem {
      .inspectContent_selectItem_qualification {
        .inspectContent_selectItem_qualification_qualified {
          margin-bottom: 10px;
        }
      }
      .inspectContent_selectItem_singleSelect {
        display: flex;
        align-items: baseline;
        .inspectContent_selectItem_singleSelect_input {
          margin-bottom: 10px;
        }
      }
      .inspectContent_selectItem_inputContent {
        .inspectContent_selectItem_inputContent_i {
          display: flex;
          align-items: center;
          margin-bottom: 10px;
          span {
            width: 50px;
          }
        }
      }
      .inspectContent_selectItem_photograph {
        .inspectContent_selectItem_photograph_i {
          display: flex;
          align-items: center;
          &>span:first-child {
            width: 160px;
          }
          .el-input__inner {
            flex-grow: 1;
          }
        }
      }
    }
    .inspectContent_button {
      display: flex;
      justify-content: flex-end;
      margin: 15px 0;
    }

  }
  .addInspectContentButton {
    display: flex;
    justify-content: center;
    padding-top: 10px;
  }

  // 隐藏数字输入框上下箭头
  /deep/ input::-webkit-outer-spin-button,
  /deep/ input::-webkit-inner-spin-button {
    -webkit-appearance: none !important;
  }
  /deep/ input[type="number"]{
    -moz-appearance: textfield;
  }
}
</style>